<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="项目名称" prop="projectName">
                <el-input
                    v-model="queryParams.projectName"
                    placeholder="请输入项目名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="项目单位" prop="projectUnit">
                <el-input
                    v-model="queryParams.projectUnit"
                    placeholder="请输入项目单位"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="项目地址" prop="projectAddress">
                <el-input
                    v-model="queryParams.projectAddress"
                    placeholder="请输入项目地址"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:project:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['business:project:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['business:project:remove']"
                >删除
                </el-button>
            </el-col>
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="warning"-->
            <!--          plain-->
            <!--          icon="el-icon-download"-->
            <!--          size="mini"-->
            <!--          @click="handleExport"-->
            <!--          v-hasPermi="['system:project:export']"-->
            <!--        >导出</el-button>-->
            <!--      </el-col>-->

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="序号" align="center" type="index" :index="calculateIndex"/>
            <!--      <el-table-column label="项目ID" align="center" prop="projectId" />-->
            <el-table-column label="项目名称" align="center" prop="projectName"/>
            <el-table-column label="项目单位" align="center" prop="projectUnit"/>
            <el-table-column label="项目地址" align="center" prop="projectAddress"/>
            <el-table-column label="报警通知" align="center" prop="isWarn">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.isWarn === '1' ? 'success' : 'danger'" disable-transitions>
                        {{ scope.row.isWarn === '1' ? '开启' : '关闭' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="短信通知" align="center" prop="smsStatus">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.smsStatus === '1' ? 'success' : 'danger'" disable-transitions>
                        {{ scope.row.smsStatus === '1' ? '开启' : '关闭' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="剩余短信(条)" align="center" prop="smsNumber">
                <template slot-scope="scope">
                    {{ scope.row.smsStatus === '1' ? scope.row.smsNumber : 0 }}
                </template>
            </el-table-column>

            <el-table-column label="管理员" align="center" prop="managerName"/>

            <!--      <el-table-column label="实图主页背景" align="center" prop="homepageImage" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <image-preview :src="scope.row.homepageImage" :width="50" :height="50"/>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <!--      <el-table-column label="气象站背景图" align="center" prop="weatherImage" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <image-preview :src="scope.row.weatherImage" :width="50" :height="50"/>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:project:edit']"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['business:project:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改项目对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="项目名称" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
                </el-form-item>
                <el-form-item label="项目单位" prop="projectUnit">
                    <el-input v-model="form.projectUnit" placeholder="请输入项目单位"/>
                </el-form-item>
                <el-form-item label="项目地址" prop="projectAddress">
                    <el-input v-model="form.projectAddress" placeholder="请输入项目地址"/>
                </el-form-item>
                <el-form-item label="管理员" prop="managerName">

                    <el-col :span="15">
                        <el-input
                            type="text"
                            placeholder="点击选择项目管理员"
                            v-model="form.managerName"
                            @click.native="allocationProjectAdmin"
                        />

                    </el-col>

                    <el-col :span="5">
                        <div style="margin-left: 5px">
                            <el-button type="primary" plain @click="clearManager">清空</el-button>
                        </div>
                    </el-col>


                </el-form-item>

                <el-form-item label="默认首页" prop="defaultIndex">
                    <el-select v-model="form.defaultIndex"
                               placeholder="默认首页"
                    >
                        <el-option
                            v-for="(item, index) in this.indexList"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="报警通知" prop="isWarn">
                    <el-radio-group v-model="form.isWarn" size="small">
                        <el-radio-button label="1">开启</el-radio-button>
                        <el-radio-button label="0">关闭</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="通知方式" v-if="form.isWarn === '1'">
                    <el-checkbox-group v-model="noticeWayList">
                        <el-checkbox label="短信"></el-checkbox>
                        <el-checkbox label="邮箱"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <!--        <el-form-item label="短信通知" prop="smsStatus">-->
                <!--          <el-radio-group v-model="form.smsStatus">-->
                <!--            <el-radio label="1">开启</el-radio>-->
                <!--            <el-radio label="0">关闭</el-radio>-->
                <!--          </el-radio-group>-->
                <!--        </el-form-item>-->

                <!--        <el-form-item label="实图主页背景图">-->
                <!--          <image-upload v-model="form.homepageImage" />-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="气象站背景图">-->
                <!--          <image-upload v-model="form.weatherImage" />-->
                <!--        </el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="allocationTitle" :visible.sync="allocationOpen" width="500px" append-to-body>
            <el-form :model="allocationQueryParams" ref="allocationQueryForm" :rules="allocationQueryRules"
                     :inline="true" label-width="85px" @submit.native.prevent
            >
                <el-form-item label="手机号码" prop="phoneNumber">
                    <el-input
                        v-model="allocationQueryParams.phoneNumber"
                        placeholder="请输入手机号码搜索用户"
                        clearable
                        size="small"
                        @keyup.enter.native="selectUser"
                    />
                </el-form-item>

                <el-form-item label="用户名称" prop="userName">
                    <el-input
                        v-model="allocationQueryParams.userName"
                        placeholder="请输入用户名称搜索用户"
                        clearable
                        size="small"
                        @keyup.enter.native="selectUser"
                    />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="selectUser">搜索</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="userList" height="250" border style="width: 100%">
                <el-table-column prop="userName" label="用户名称" align="center" width="150"/>
                <el-table-column prop="phoneNumber" label="手机号码" align="center" width="200"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button type="primary" size="small" @click="choose(scope.row)">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

    </div>
</template>

<script>
import { pageListProject, getProject, delProject, addProject, updateProject } from '@/api/business/project'
import { listUser2 } from '@/api/system/user'
import { listTIndex } from '@/api/business/showIndex'
import store from '../../../store'

export default {
    inject: ['reload'],
    name: 'List',
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 项目表格数据
            projectList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                projectName: null,
                projectUnit: null,
                projectAddress: null,
                smsStatus: null,
                smsNumber: null,
                homepageImage: null,
                weatherImage: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {},
            allocationTitle: '',
            allocationOpen: false,
            allocationQueryParams: {
                pageNum: 1,
                pageSize: 10,
                phoneNumber: null,
                userName: null
            },
            allocationQueryRules: {
                // phoneNumber: [
                //   { required: true, trigger: 'blur', message: '请输入手机号码' }
                // ]
            },
            userList: null,
            managerProject: {
                managerId: null,
                projectId: null
            },
            noticeWayList: [],
            indexList: []
        }

    },
    created() {
        this.getList()
        this.getIndexList()
    },
    methods: {
        calculateIndex(index) {
            const pageNum = this.queryParams.pageNum
            const pageSize = this.queryParams.pageSize
            return index + 1 + (pageNum - 1) * pageSize
        },
        /** 查询项目列表 */
        getList() {
            this.loading = true
            pageListProject(this.queryParams).then(response => {
                this.projectList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                projectId: null,
                projectName: null,
                projectUnit: null,
                projectAddress: null,
                isWarn: '0',
                smsStatus: '0',
                emailNotice: '0',
                smsNumber: null,
                homepageImage: null,
                weatherImage: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null
            }
            this.noticeWayList = []
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.projectId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加项目'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const projectId = row.projectId || this.ids

            getProject(projectId).then(response => {
                this.form = response.data

                if (this.form.isWarn === '1') {
                    if (this.form.smsStatus === '1') {
                        this.noticeWayList.push('短信')
                    }
                    if (this.form.emailNotice === '1') {
                        this.noticeWayList.push('邮箱')
                    }
                }

                console.log(this.noticeWayList)

                this.open = true
                this.title = '修改项目'
            })
        },
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.projectId != null) {

                        this.form.smsStatus = '0'
                        this.form.emailNotice = '0'

                        if (this.form.isWarn === '1') {

                            if (this.noticeWayList.length === 0) {
                                this.$modal.msgError('请选择通知方式')
                                return
                            }

                            this.noticeWayList.forEach(item => {

                                if ('短信' === item) {
                                    this.form.smsStatus = '1'
                                }

                                if ('邮箱' === item) {
                                    this.form.emailNotice = '1'
                                }

                            })

                        }

                        updateProject(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })

                    } else {

                        if (this.form.isWarn === '1') {

                            if (this.noticeWayList.length === 0) {
                                this.$modal.msgError('请选择通知方式')
                                return
                            }

                            this.noticeWayList.forEach(item => {

                                if ('短信' === item) {
                                    this.form.smsStatus = '1'
                                }

                                if ('邮箱' === item) {
                                    this.form.emailNotice = '1'
                                }

                            })

                        }

                        addProject(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        handleDelete(row) {
            const projectIds = row.projectId || this.ids
            this.$modal.confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？').then(function() {
                return delProject(projectIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
                if (projectIds.includes(sessionStorage.getItem('projectId'))) {
                    console.log('包含.....')
                    sessionStorage.removeItem('projectId')
                }
                if (projectIds.includes(store.getters.projectId)) {
                    this.$store.dispatch('setProjectId', null)
                }
                // 刷新页面
                this.reload()
            }).catch(() => {
            })
        },
        handleExport() {
            this.download('system/project/export', {
                ...this.queryParams
            }, `project_${new Date().getTime()}.xlsx`)
        },
        allocationProjectAdmin() {
            this.allocationTitle = '分配项目管理员'
            this.allocationOpen = true
            this.managerProject.projectId = parseInt(this.ids[0])

        },
        selectUser() {
            if (this.allocationQueryParams.userName != null || this.allocationQueryParams.phoneNumber != null) {
                listUser2(this.allocationQueryParams).then(response => {
                        if (response.rows.length === 0) {
                            this.$message.info('该用户不存在')
                        }
                        this.userList = response.rows
                    }
                )
            } else {
                this.$message.warning('请输入手机号或者用户名查询用户')
            }
        },
        getIndexList() {

            listTIndex(null).then(response => {
                // console.log(response)

                for (let item of response.rows) {
                    let temp = {}
                    temp['value'] = item.indexUrl
                    temp['label'] = item.indexName

                    this.indexList.push(temp)
                }

            })
        },

        clearManager() {
            this.form.managerId = null
            this.form.managerName = null
        },

        choose(row) {

            this.form.managerId = row.userId
            this.form.managerName = row.userName

            this.allocationOpen = false
            this.allocationQueryParams.phoneNumber = null
            this.allocationQueryParams.userName = null
            this.userList = null

        }
    }
}
</script>
